package simulator.request;

import simulator.data.HttpData;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * Simulate HTTP get request
 */
public class PostRequest implements Runnable {

    private final CountDownLatch startSignal;
    private String target;
    private ArrayList<HttpData> parameters;

    public PostRequest(CountDownLatch startSignal) {
        this.startSignal = startSignal;
    }

    public PostRequest(CountDownLatch startSignal, String target, ArrayList<HttpData> parameters) {
        this.startSignal = startSignal;
        this.target = target;
        this.parameters = parameters;
    }

    @Override
    public void run() {
        try {
            startSignal.await();
            System.out.println(sendPostRequest(target, parameters));
        } catch (InterruptedException ex) {
            Logger.getLogger(PostRequest.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private String sendPostRequest(String target, ArrayList<HttpData> parameters) {

        String urlParameters = "";
        for (int i = 0; i < parameters.size(); i++) {
            HttpData data = parameters.get(i);
            urlParameters += "&" + data.getParameter() + "=" + data.getValue();
        }

        URL url;
        HttpURLConnection connection = null;
        try {
            //Create connection
            url = new URL(target);
            connection = (HttpURLConnection) url.openConnection();

            //Set request properties
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded");

            connection.setRequestProperty("Content-Length", ""
                    + Integer.toString(urlParameters.getBytes().length));
            connection.setRequestProperty("charset", "utf-8");
            connection.addRequestProperty("Accept-Language", "en-US,en;q=0.8");
            connection.addRequestProperty("User-Agent", "Mozilla");

            connection.setUseCaches(false);
            connection.setDoOutput(true);

            System.out.println(connection.getURL());

            //Send request
            try (DataOutputStream wr = new DataOutputStream(
                    connection.getOutputStream())) {
                wr.writeBytes(urlParameters);
                wr.flush();
            }

            System.out.println(connection.getResponseCode());
            //Get Response	
            InputStream is = connection.getInputStream();
            StringBuffer response;
            try (BufferedReader rd = new BufferedReader(new InputStreamReader(is))) {
                String line;
                response = new StringBuffer();
                while ((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
            }
            return response.toString();

        } catch (Exception e) {
            return null;

        } finally {

            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}
